package com.jp.knowledge.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.AttentionDetailActivity;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.adapter.AttentionItemAdapter;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.AttentionData;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.util.L;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.WrapListView;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jiayen on 16/10/27.
 * <p>
 * 关注各模块fragment
 */

public class AttentionItemFragment extends BaseFragment implements ResultSubscriber.OnResultListener, CanRefreshLayout.OnLoadMoreListener, CanRefreshLayout.OnRefreshListener, View.OnClickListener {

    private final int ATTENTION_LIST_CODE = 0x00000001;     //获取列表
    private final int ATTENTION_DELETE_CODE = 0x00000002;   //获取列表

    private View mView;
    @ViewInject(R.id.can_content_view)
    private WrapListView listView;
    @ViewInject(R.id.refresh)
    private CanRefreshLayout mRefresh;
    @ViewInject(R.id.attention_btn)
    private TextView attentionBtn;
    @ViewInject(R.id.no_attention_layout)
    private LinearLayout noContentLayout;

    private Context mContext;
    private int flag;//标识（0-主题，1-产品，2-公司，3-人物，4-频道）
    private List<AttentionData> list;
    private AttentionItemAdapter adapter;
    private boolean fresh;//是否是刷新
    private boolean isFirst = true;//是否是第一次加载

    private LocalBroadcastManager localBroadcastManager;
    private LocalBroadCast localBroadCast;
    private CommDialog itemDeleteDialog;

    public AttentionItemFragment addFalg(int flag) {
        if(flag == 0)
            isFirst = false;
        this.flag = flag;
        return this;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.attention_fragment_item, null);
        this.mContext = getActivity();
        x.view().inject(this, mView);
        initData();
        initBroadCast();
        itemDeleteDialog = new CommDialog(mContext);
        itemDeleteDialog.setRightListener(this);
        itemDeleteDialog.setTag(0);
        return mView;
    }

    @Override
    public void onDestroy() {
        localBroadcastManager.unregisterReceiver(localBroadCast);
        super.onDestroy();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        list = new ArrayList<>();
        adapter = new AttentionItemAdapter(mContext, list, flag);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if(application.getUserData() == null || application.getUserData().getAuditStete() != 1){
                    ToasUtil.toast(mContext, "加入公司审核通过后才能查，请等候");
                    return;
                }
                Intent intent = new Intent(mContext, AttentionDetailActivity.class);
                intent.putExtra("infoId", list.get(i).getId());
                intent.putExtra("type", list.get(i).getType());
                intent.putExtra("prompt", list.get(i).getPrompt());
                intent.putExtra("createType", list.get(i).getCreateType());
                intent.putExtra("icon", list.get(i).getIcon());
                intent.putExtra("title", list.get(i).getTitle());
                startActivity(intent);
                list.get(i).setNewNum(0);
                adapter.notifyDataSetChanged();
            }
        });
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if(flag != 1 && flag != 2 && flag != 3)
                    return false;
                itemDeleteDialog.setTag(position);
                itemDeleteDialog.setContent("是否取消关注 \"" + list.get(position).getTitle() + "\" ？");
                itemDeleteDialog.show();
                return true;
            }
        });
        mRefresh.setRefreshEnabled(true);
        mRefresh.setLoadMoreEnabled(false);
        mRefresh.setOnLoadMoreListener(this);
        mRefresh.setOnRefreshListener(this);
        getData(0);
    }

    private void initBroadCast(){
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
            @Override
            public void done(Context context, Intent intent) {
                String action = intent.getAction();
                if(LocalBroadCast.ATTENTION_EVENT_BROAD.equals(action)){
                    String id = intent.getStringExtra("id");
                    int isSubscribe = intent.getIntExtra("isSubscribe", 1);
                    if(isSubscribe == 0 && id != null && list != null && list.size() > 0) {
                        for (AttentionData attentionData : list)
                            if (id.equals(attentionData.getId())) {
                                list.remove(attentionData);
                                adapter.notifyDataSetChanged();
                                break;
                            }
                    } else if(isSubscribe == 1){
                        mRefresh.autoRefresh();
                    }
                } else if(LocalBroadCast.LOGOUT_SUCCESS_BROD.equals(action)){
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocalBroadCast.ATTENTION_EVENT_BROAD);
        intentFilter.addAction(LocalBroadCast.LOGOUT_SUCCESS_BROD);
        localBroadcastManager.registerReceiver(localBroadCast, intentFilter);
    }

    public void refresh(int mode, boolean fresh){
        isFirst = fresh;
        getData(mode);
    }

    /**
     * 获取数据
     */
    public void getData(int mode) {
        if(mode == 0)
            fresh = true;
        else
            fresh = false;

        long time = System.currentTimeMillis();
        if(mode == 0 && list != null && list.size() > 0)   //刷新拿第一条
            time = list.get(0).getAttentionTime();
        else if (mode == 1 && list != null && list.size() > 0)       //加载更多拿最后一条
            time = list.get(list.size() - 1).getAttentionTime();

        HttpHelper http = HttpHelper.getInstance(mContext);
        JsonObject param = new JsonObject();
        param.addProperty("count", 20);
        param.addProperty("mode", mode);
        param.addProperty("time", time);
        switch (flag) {
            case 0://主题
                http.subscribeThemeList(param, ATTENTION_LIST_CODE, this);
                break;
            case 1://公司
                http.subscribecompanyList(param, ATTENTION_LIST_CODE, this);
                break;
            case 2://产品
                http.subscribeproductList(param, ATTENTION_LIST_CODE, this);
                break;
            case 3://人物
                http.subscribefigureList(param, ATTENTION_LIST_CODE, this);
                break;
            case 4://频道
                http.subscribechannelList(param, ATTENTION_LIST_CODE, this);
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() != R.id.right_btn)
            return;
        int position = (int) itemDeleteDialog.getTag();

        JsonObject param = new JsonObject();
        param.addProperty("token", HttpHelper.token);
        param.addProperty("id",list.get(position).getId());
        param.addProperty("type", list.get(position).getType());
        HttpHelper.getInstance(mContext).subscribeOperate(param, ATTENTION_DELETE_CODE, this);

        list.remove(position);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onStart(int requestType) {
        if(isFirst)
            isFirst = false;
    }

    @Override
    public void onCompleted(int requestType) {
        if (requestType == ATTENTION_LIST_CODE) {
            try {
                mRefresh.refreshComplete();
                mRefresh.loadMoreComplete();
            } catch (Exception e) {
                L.e(e.toString());
            }
        }
    }

    @Override
    public void onError(int requestType) {
        if (requestType == ATTENTION_LIST_CODE)
            noContentLayout.setVisibility(View.VISIBLE);
        onCompleted(requestType);
    }

    @Override
    public void onNext(IModel data, int requestType) {
        if (data.getErrcode() != 0){
            noContentLayout.setVisibility(View.VISIBLE);
            onError(requestType);
            return;
        }
        if (requestType == ATTENTION_LIST_CODE) {
            List<AttentionData> temp = data.getList(AttentionData.class);
            if (fresh) {
                list = temp;
                if(list == null)
                    list = new ArrayList<>();
                noContentLayout.setVisibility(list.size()==0 ? View.VISIBLE : View.GONE);
            } else {
                if(list == null)
                    list = new ArrayList<>();
                if(temp != null && temp.size() > 0)
                    list.addAll(temp);
                noContentLayout.setVisibility(list.size()==0 ? View.VISIBLE : View.GONE);
            }
            adapter.updataAdapter(list);
        } else if(requestType == ATTENTION_DELETE_CODE){

        }
    }

    @Override
    public void onLoadMore() {
        fresh = false;
        getData(1);
    }

    @Override
    public void onRefresh() {
        fresh = true;
        getData(0);
    }
}
